import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_demo/utils/shared_preferences.dart';

class SearchHistory {
  final String name;
  final String targetRouter;

  SearchHistory({@required this.name, @required this.targetRouter});
}

class SearchHistoryList {
  static String searchHistory = 'searchHistory';
  static SpUtil _sp;
  static SearchHistoryList _instance;
  static List<SearchHistory> _searchHistoryList = [];

  static SearchHistoryList _getInstance(SpUtil sp) {
    if (_instance == null) {
      _sp = sp;
      String json = sp.get(SharedPreferencesKeys.searchHistory);
      _instance = SearchHistoryList._formJson(json);
    }
    return _instance;
  }

  ///从一个json中，构造SearchHistoryList对象,这里是私有的构造方法
  SearchHistoryList._formJson(String jsonData) {
    _searchHistoryList = [];
    if (jsonData == null) return;
    List list = json.decode(jsonData);

    list.forEach((item) {
      _searchHistoryList.add(SearchHistory(
          name: item['name'], targetRouter: item['targetRouter']));
    });
  }

  factory SearchHistoryList([SpUtil sp]) {
    if (sp == null && _instance == null) {
      print(AssertionError(
          'SearchHistoryList need instantiatied SpUtil at first timte '));
    }
    return _getInstance(sp);
  }

  //存放的最大数量
  int _count = 10;

  List<SearchHistory> getList() => _searchHistoryList;

  clear() {
    _sp.remove(SharedPreferencesKeys.searchHistory);
    _searchHistoryList = [];
  }

  save() {
    _sp.putString(SharedPreferencesKeys.searchHistory, this.toJson());
  }

  ///add,最大存10个
  add(SearchHistory item) {
    if (!_searchHistoryList.contains(item)) {
      if (_searchHistoryList.length >= _count) {
        _searchHistoryList.removeAt(0);
      }
      _searchHistoryList.add(item);
      save();
    }
  }

  ///将list转为字符串
  String toJson() {
    List<Map<String, String>> list = [];
    _searchHistoryList.forEach((item) {
      list.add({'name': item.name, 'targetRouter': item.targetRouter});
    });
    return json.encode(list);
  }

  @override
  String toString() {
    return toJson();
  }
}
